<template>
  <div>
    <div class="tools">
      <el-button @click="handleAdd"> 添加角色 </el-button>
    </div>
    <RoleTable :data="roles">
      <template #end>
        <el-table-column align="center" width="250" label="操作" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleRemove(scope.row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </RoleTable>
    <Pagination
      v-model:current-page="paginationData.currentPage"
      v-model:page-size="paginationData.pageSize"
      :total="paginationData.total"
      :load-list="getTableData"
    />
    <UnAddRole
      :ou-id="props.ou.id"
      v-model:visible="visible"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { PropType, reactive, ref, watch } from 'vue'

import Pagination from '@/components/Pagination/index.vue'
import { getAddedRoles, removeRoleFromDepartment } from '@/http/department'
import { IDepartment } from '@/http/types/department'
import { IRole } from '@/http/types/role'
import RoleTable from '@/views/system/identity/role/RoleTable.vue'

import UnAddRole from './unAddRole.vue'

const props = defineProps({
  ou: {
    type: Object as PropType<IDepartment>,
    required: true,
  },
})

const visible = ref(false)
const paginationData = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
})
const roles = ref<IRole[]>([])
watch(
  () => props.ou.id,
  () => {
    getTableData()
  },
)
const getTableData = async () => {
  if (!props.ou.id) return ElMessage.error('请选择部门')
  const res = await getAddedRoles(
    paginationData.currentPage,
    paginationData.pageSize,
    props.ou.id,
  )
  roles.value = res.items
  paginationData.total = res.totalCount
}
const handleRemove = (row: IRole) => {
  ElMessageBox.confirm('从部门移除该角色, 是否继续?', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
  }).then(async () => {
    if (!row.id) return
    await removeRoleFromDepartment(row.id, props.ou.id)
    getTableData()
  })
}
const handleAdd = () => {
  if (!props.ou.id) return ElMessage.error('请选择部门')
  visible.value = true
}
const handleSuccess = () => {
  visible.value = false
  getTableData()
}
</script>

<style scoped lang="scss">
.tools {
  margin-bottom: 20px;
}
</style>
